﻿using BigMonitoringWarningApi.Model.ApiResult;
using GYCTOAManagementSystemNewApi.Model;
using GYCTOAManagementSystemNewApi.Model.Entity; 
using GYCTOAManagementSystemNewApi.Model.Enum.PayrollForm;
using GYCTOAManagementSystemNewApi.Model.Request;
using GYCTOAManagementSystemNewApi.Model.Response;
using GYCTOAManagementSystemNewApi.Model.Tool;
using GYCTOAManagementSystemNewApi.Public;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Microsoft.SqlServer.Server;
using Microsoft.VisualBasic;
using Newtonsoft.Json;
using NuGet.Packaging;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using GYCTOAManagementSystemNewApi.Tool;
using GYCTOAManagementSystemNewApi.Model.Enum.Livingexpenses;

namespace GYCTOAManagementSystemNewApi.Controllers
{
    /// <summary>
    ///生活费
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class LivingexpensesController : ControllerBase
    {
        private readonly ILogger<DocumentController> _logger;
        DBContext _db;
        PublicTool _publictool;
        public LivingexpensesController(ILogger<DocumentController> logger, DBContext db)
        {
            _logger = logger;
            _db = db;
            _publictool = new PublicTool(_db);
        }

        /// <summary>
        ///获取审批类型类型
        /// </summary>
        /// <returns></returns>
        [HttpPost("GetLivingOrderStateResponse")]
        public ApiResult GetLivingOrderStateResponse()
        {
            var type = typeof(LivingOrderStateEnum);
            var data = Enum.GetValues(type)
                       .Cast<LivingOrderStateEnum>()
                       .Select(e => new GetEnumtResponse
                       {
                           Description = command.GetEnumDescription(e),
                           Value = Convert.ToInt32(e),
                       })
                       .ToList();

            return ApiResult.True(data);
        }
        /// <summary>
        /// 获取生活费人员列表
        /// </summary>
        /// <returns></returns>
        [HttpPost("CreateGetLivingexpensesUsers")]
        public ApiResult CreateGetLivingexpensesUsers()
        {
            var author = HttpContext.Request.Headers["Authorization"].ToString().Split(' ')[1];
            var userid = Convert.ToInt32(TokenManage.GetTokenValues(author)[0].Value);
            var roleids = Convert.ToInt32(TokenManage.GetTokenValues(author)[5].Value);
            List<int> ints = new List<int>();
            ints.Add(userid);
            var role = Convert.ToString((TokenManage.GetTokenValues(author)[2].Value));
            var ids = ConfigurationHelper.GetConfigHeadRoleId("HeadRoleId");
            var financialId = ConfigurationHelper.GetConfigHeadRoleId("FinancialId");
            //最高权限获取所有人员列表
            if (role.Contains(PublicTool.Admin)|| roleids.ToString() == financialId)
            {
                var data = _db.Users.Where(x => !x.Delete).ToList();
                return ApiResult.True(data);
            }
            var projectlist = _db.Project.Where(x => userid.Equals(Convert.ToInt32(x.HeadUserId)) && !x.Delete).ToList();
            var Userids = projectlist.Select(x => x.UserIds).ToList();
            //获取人员项目列表下所有的人员信息
            foreach (var item in Userids)
            {
                if (!string.IsNullOrEmpty(item))
                {
                    var data = item.Split(',').Select(int.Parse).ToList();
                    ints.AddRange(data);
                }
            }
            var users = _db.Users.Where(x => ints.Distinct().ToList().Contains(x.Id)).ToList();
            return ApiResult.True(users);
        }
          
        /// <summary>
        /// 获取生活费列表
        /// </summary>
        /// <returns></returns>
        [HttpPost("GetLivingexpenses")]
        public ApiPageResult GetLivingexpenses([FromBody] GetLivingexpensesRequest request)
        {

            var author = HttpContext.Request.Headers["Authorization"].ToString().Split(' ')[1];
            var userid = Convert.ToInt32(TokenManage.GetTokenValues(author)[0].Value);
            var roleids = Convert.ToInt32(TokenManage.GetTokenValues(author)[5].Value);
            List<int> userids = new List<int>();
            userids.Add(userid);  
            var role = Convert.ToString((TokenManage.GetTokenValues(author)[2].Value));  
            var ids = ConfigurationHelper.GetConfigHeadRoleId("HeadRoleId");
            var financialId = ConfigurationHelper.GetConfigHeadRoleId("FinancialId"); 
        

                var livingexpenses = _db.Livingexpenses.Where(x => !x.Delete).AsEnumerable();
            if ( (request.DateYear.HasValue))
            {
                livingexpenses = livingexpenses.AsEnumerable().Where(x => Convert.ToDateTime(x.LivingeBatch).Year == request.DateYear);
            }
            if (  (request.DateMon.HasValue))
            {
                livingexpenses = livingexpenses.AsEnumerable().Where(x => Convert.ToDateTime(x.LivingeBatch).Month == request.DateMon);
            }
            if ( request.DateDay.HasValue)
            {
                livingexpenses = livingexpenses.AsEnumerable().Where(x => Convert.ToDateTime(x.LivingeBatch).Day == request.DateDay);
            }
            if (request.OrderStatus.HasValue)
            {
                livingexpenses = livingexpenses.AsEnumerable().Where(x => (int)x.OrderStatus==  request.OrderStatus);
            }
            if (!string.IsNullOrWhiteSpace(request.settlementNumber))
            {
                livingexpenses = livingexpenses.AsEnumerable().Where(x => x.SettlementNumber == request.settlementNumber);
            }
            var livingexpensesInfo = _db.LivingexpensesInfo.Where(x => !x.Delete).ToList();
            //最高权限获取所有人员列表
            if (!(role.Contains(PublicTool.Admin) || roleids.ToString() == financialId))
            {
                var projectlist = _db.Project.Where(x => userid.Equals(Convert.ToInt32(x.HeadUserId)) && !x.Delete).ToList();
                var Userids = projectlist.Select(x => x.UserIds).ToList();
                //获取人员项目列表下所有的人员信息
                foreach (var item in Userids)
                {
                    if (!string.IsNullOrEmpty(item))
                    {
                        var data = item.Split(',').Select(int.Parse).ToList();
                        userids.AddRange(data);
                    }
                    livingexpensesInfo = livingexpensesInfo.Where(x => userids.Contains(x.UserId)).ToList();
                }
            }

            var result1= livingexpenses.ToList();
            var Data = from DataList in livingexpenses.ToList()
                        join info in livingexpensesInfo on DataList.Id equals info.LivingexpensesId into info
                        select new {

                            Id= DataList.Id,  
                            Settlement= DataList.Settlement,
                            SettlementNumber= DataList.SettlementNumber,
                            LivingeBatch = DataList.LivingeBatch,
                            OrderStatus= DataList.OrderStatus,
                            Money = info.Sum(x=>x.Money).ToString("0.00"),
                            count= info.Count(),
                        };
            var result = Data.Where(x=>x.Money!="0.00").OrderByDescending(x=>x.LivingeBatch).ToList();
            var rows = result.Skip(request.PageSize * (request.PageIndex - 1)).Take(request.PageSize).ToList();
            //return ApiPageResult.False(new { }, Data.PageIndex, Data.PageSize, $"程序出现问题,请联系开发相关人员");
            return ApiPageResult.True(rows, request.PageIndex, request.PageSize, result.Count);
        }
            /// <summary>
            /// 获取生活费人员列表
            /// </summary>
            /// <returns></returns>
            [HttpPost("GetLivingexpensesUsers")]
        public ApiResult GetLivingexpensesUsers([FromBody] GetLivingexpensesUsersRequest request)
        {
            try
            {
                var author = HttpContext.Request.Headers["Authorization"].ToString().Split(' ')[1];
                var userid = Convert.ToInt32(TokenManage.GetTokenValues(author)[0].Value);
                var role = Convert.ToString((TokenManage.GetTokenValues(author)[2].Value));
                var Roles = TokenManage.GetTokenValues(author)[5].Value;
                List<int> ints = new List<int>(); ints.Add(userid);
                var headRoleId = ConfigurationHelper.GetConfigHeadRoleId("HeadRoleId");
                var financialId = ConfigurationHelper.GetConfigHeadRoleId("FinancialId");
                if (headRoleId.Contains(Roles))
                {
                    var projectlist = _db.Project.Where(x => userid.Equals(Convert.ToInt32(x.HeadUserId))&&!x.Delete).ToList();
                    var Userids = projectlist.Select(x => x.UserIds).ToList();
                    //获取人员项目列表下所有的人员信息
                    foreach (var item in Userids)
                    {
                        if (!string.IsNullOrEmpty(item))
                        {

                            var itemlist = item.Split(',').Select(int.Parse).ToList();
                            ints.AddRange(itemlist);
                        }
                    }
                }
               var livingexpenses = _db.Livingexpenses.FirstOrDefault(x => x.LivingeBatch == request.LivingeBatch);
               if (livingexpenses == null)
                {
                  return ApiResult.True(new LivingexpensesResponse());
               }
               var livingexpensesinfo = _db.LivingexpensesInfo.Where(x => x.LivingexpensesId == livingexpenses.Id).ToList();
                if (!(role.Contains(PublicTool.Admin) || Roles.Contains(financialId)))
                {
                    livingexpensesinfo = livingexpensesinfo.Where(x => ints.Distinct().ToList().Contains(x.UserId)).ToList();
                    
                }
                //当状态待为财务发放数据后 没有发放工资的数据 不返回
                if (livingexpenses.OrderStatus == RealOrderStateEnum.FinanceSuccess)
                {
                    livingexpensesinfo = livingexpensesinfo.Where(x => x.Money != 0).ToList();
                }
                var data = new LivingexpensesResponse()
               {
                   Livingexpenses = livingexpenses,
                   Livingexpensesinfo = livingexpensesinfo,
               };
                return ApiResult.True(data);
            }
            catch (Exception)
            {
                return ApiResult.False("当前批次暂无数据");
                throw;
            }
        }

        /// <summary>
        /// 导出生活费工资表
        /// </summary>
        /// <returns></returns>
        [HttpPost("ExportLivingexpenses")]
        public ApiResult ExportLivingexpenses([FromBody] ExportLivingexpensesRequest request)
        {

            if (request.LivingeId==0)
            {
                return ApiResult.False("请选择对应的项目");
            }
            var livingexpenses = _db.Livingexpenses.FirstOrDefault(x => x.Id.Equals(request.LivingeId));
            var author = HttpContext.Request.Headers["Authorization"].ToString().Split(' ')[1];
            var role = Convert.ToString((TokenManage.GetTokenValues(author)[2].Value));
            var right = Convert.ToString(TokenManage.GetTokenValues(author)[5].Value);
            var financialId = ConfigurationHelper.GetConfigHeadRoleId("FinancialId");
            if (!(role.Contains(PublicTool.Admin) || right.Contains(financialId)))
            {
                return ApiResult.False("您当前暂无权限导出项目");
            }
           //if (livingexpenses.OrderStatus != RealOrderStateEnum.FinanceSuccess)
           //{
           //    return ApiResult.False("该订单状态未达到财务审核状态，请审核完成后导出");
           //}
            var userList = _db.Users.ToList();
            var requestList = _db.LivingexpensesInfo.Where(x => x.LivingexpensesId.Equals(request.LivingeId) && !x.Delete).ToList();
            List<ExportRequestProp> props = new();
            foreach (var exportRequestProp in requestList)
            {
                var user = userList.FirstOrDefault(x => x.Id.Equals(exportRequestProp.UserId));
                props.Add(new ExportRequestProp()
                {
                    LivingeId = request.LivingeId,
                    Money = exportRequestProp.Money ,
                    LivingeBatch = livingexpenses.LivingeBatch,
                    UserName = user.UserName,
                    BankCardNumber = user.BankCardNumber
                });
            }
            var relust = new PublicTool().CreateExcelToLiving(props);
            return ApiResult.True(relust);
        }

         
        /// <summary>
        /// 检查当前数据是否已经开帐
        /// </summary>
        /// <returns></returns>
        [HttpPost("CheckSettlement")]
        public ApiResult CheckSettlement([FromBody] CheckSettlementRequest request)
        {
          var Checksettlement  =_db.Livingexpenses.FirstOrDefault(x=>x.SettlementNumber==request.SettlementNumber
          && x.Settlement && !x.Delete  );
            if (Checksettlement != null)
            {
                return ApiResult.False($"当前年份编号{Checksettlement.LivingeBatch}已开帐，是否修改开帐订单,修改后社保数据将清除重新开帐时请重新填写.");
            } 
             return ApiResult.True();
        }

        /// <summary>
        /// 修改已经开帐的生活费,请谨慎操作
        /// </summary>
        /// <returns></returns>
        [HttpPost("UpSettlement")]
        public ApiResult UpSettlement([FromBody] CheckSettlementRequest request)
        {
            var Checksettlement = _db.Livingexpenses.FirstOrDefault(x => x.SettlementNumber == request.SettlementNumber
            && x.Settlement && !x.Delete  );
         
            if (Checksettlement == null)
            {
                return ApiResult.True();
            }
            Checksettlement.Settlement = false;
            var LivingexpensesInfoList= _db.LivingexpensesInfo.Where(x => x.LivingexpensesId == Checksettlement.Id).ToList();
            LivingexpensesInfoList.ForEach(x =>
             {
                 x.Settlement = false; 
             });
            _db.Livingexpenses.Update(Checksettlement);
            _db.LivingexpensesInfo.UpdateRange(LivingexpensesInfoList);
            _db.SaveChanges();
            return ApiResult.True();
        }

        private void HandleUpdateNewYear<T>(List<Livingexpenses> Kzsj, List<Livingexpenses> Finlist, Livingexpenses ChecksettlementById, SetSettlementRequest request)
        {
             

            List<Livingexpenses> UpdateDate;
            string lastYear = ChecksettlementById.SettlementNumber;
            var Yearlist = Kzsj.Select(x => Convert.ToInt32(x.SettlementNumber)).Distinct().ToList();
            Yearlist.Add(Convert.ToInt32(request.SettlementNumber));
            Yearlist.Sort();
            var index = Yearlist.FindIndex(x => x == Convert.ToInt32(request.SettlementNumber));
            if (index == 0 && Yearlist.Count != 1)
            {
                var headerDate = Finlist.Where(x => x.SettlementNumber.Equals(Yearlist[index + 1].ToString()) && x.Settlement && !x.Delete).FirstOrDefault();
                UpdateDate = Finlist.Where(x => x.LivingeBatch.ToDate() >= ChecksettlementById.LivingeBatch.ToDate() && x.LivingeBatch.ToDate() < headerDate.LivingeBatch.ToDate()).ToList();
            }
            else if (index == Yearlist.Count - 1)
            {
                UpdateDate = Finlist.Where(x => x.LivingeBatch.ToDate() >= ChecksettlementById.LivingeBatch.ToDate()).ToList();
            }
            else
            {
                var headerDate = Finlist.Where(x => x.SettlementNumber.Equals(Yearlist[index + 1].ToString()) && x.Settlement && !x.Delete).FirstOrDefault();
                UpdateDate = Finlist.Where(x => x.LivingeBatch.ToDate() >= ChecksettlementById.LivingeBatch.ToDate() && x.LivingeBatch.ToDate() < headerDate.LivingeBatch.ToDate()).ToList();
            }
            UpdateSettlementRecords(UpdateDate, request.SettlementNumber, request);
        }

        private void UpdateSettlementRecords(List<Livingexpenses> UpFinanceReimbursementReims, string SettlementNumber, SetSettlementRequest request)
        {
            foreach (var item in UpFinanceReimbursementReims)
            {
                if (request.OrderId == item.Id) item.Settlement = true;
                else item.Settlement = false;
                item.SettlementNumber = SettlementNumber;
                UpdateReimRule(item.Id, SettlementNumber);
                _db.Livingexpenses.Update(item);
            }
        }
        private void UpdateReimRule(int LivingexpensesId, string SettlementNumber)
        {
            var orderInfo = _db.LivingexpensesInfo
                .Where(x => x.LivingexpensesId == LivingexpensesId)
                .ToList();
            orderInfo.ForEach(x => x.SettlementNumber = SettlementNumber);
            _db.LivingexpensesInfo.UpdateRange(orderInfo);
        }
        private void HandleExistingSettlement(
      Livingexpenses OldChecksettlement,
      Livingexpenses NewChecksettlementById,
      List<Livingexpenses> settlements,
      int index,
      SetSettlementRequest request,
      out List<Livingexpenses> UpLivingexpensess,
      out string SettlementNumber)
        {
          
            int numberIndex = settlements.FindIndex(x => x.SettlementNumber.Equals(request.SettlementNumber));
            var Livingexpenses = _db.Livingexpenses.ToList();
            if (OldChecksettlement.LivingeBatch.ToDate() > NewChecksettlementById.LivingeBatch.ToDate())
            {
                SettlementNumber = request.SettlementNumber;
                //不是最大,也不是最小
                if (numberIndex != 0)
                {
                    UpLivingexpensess = Livingexpenses.Where(x => x.LivingeBatch.ToDate() >= NewChecksettlementById.LivingeBatch.ToDate() && x.LivingeBatch.ToDate() <= OldChecksettlement.LivingeBatch.ToDate()).ToList();

                }
                else
                {
                    UpLivingexpensess = Livingexpenses.Where(x => x.LivingeBatch.ToDate() >= NewChecksettlementById.LivingeBatch.ToDate()).ToList();
                }
            }
            else if (OldChecksettlement.LivingeBatch.ToDate() < NewChecksettlementById.LivingeBatch.ToDate())
            {
                //最小年份
                if ((numberIndex + 1) == settlements.Count)
                {
                    int.TryParse(settlements[index].SettlementNumber, out var number);
                    throw new Exception($"当前无 ：{number - 1}年度信息，当前开账无法前移 ");
                }
                //中间,最大 年份(都是改变中间的差值)
                else
                {
                    UpLivingexpensess = Livingexpenses.Where(x => x.LivingeBatch.ToDate() < NewChecksettlementById.LivingeBatch.ToDate() && x.LivingeBatch.ToDate() >= OldChecksettlement.LivingeBatch.ToDate()).ToList();
                    //往上移动时间,需要修改的数据就变成去年的时间
                    SettlementNumber = settlements[numberIndex + 1].SettlementNumber;
                }
            }
            else
            {
                //最大年开账
                if (numberIndex == 0)
                {
                    UpLivingexpensess = Livingexpenses.Where(x => x.LivingeBatch.ToDate() >= NewChecksettlementById.LivingeBatch.ToDate()).ToList();
                    //往上移动时间,需要修改的数据就变成去年的时间
                    SettlementNumber = request.SettlementNumber;
                }
                else
                {
                    var fendingtime = settlements[numberIndex - 1].LivingeBatch.ToDate();
                    UpLivingexpensess = Livingexpenses.Where(x => x.LivingeBatch.ToDate() >= NewChecksettlementById.LivingeBatch.ToDate() && x.LivingeBatch.ToDate() < fendingtime).ToList();
                    //往上移动时间,需要修改的数据就变成去年的时间
                    SettlementNumber = request.SettlementNumber;
                }
            }
        }

        private void UpdateTargetRecord(SetSettlementRequest request, Livingexpenses ChecksettlementById)
        {
            ChecksettlementById.SettlementNumber = request.SettlementNumber;
            ChecksettlementById.Settlement = true;

            var orderInfoById = _db.LivingexpensesInfo
                .Where(x => x.LivingexpensesId == ChecksettlementById.Id)
                .ToList();
            orderInfoById.ForEach(x => x.SettlementNumber = request.SettlementNumber);
            _db.LivingexpensesInfo.UpdateRange(orderInfoById);
            _db.Livingexpenses.Update(ChecksettlementById);
        }
        /// <summary>
        /// 添加开账,设置开账数据；2025年7月25日弃用，将之前的批量年度开账改为单条记录单独开账
        /// </summary>
        /// <returns></returns>
        [HttpPost("SetSettlement1")]
        public ApiResult SetSettlement1([FromBody] SetSettlementRequest request)
        {
            try
            {
                using (var transaction = _db.Database.BeginTransaction())
                {
                    try
                    {
                        var livingexpenses = _db.Livingexpenses.ToList();
                        // 获取年份结算数据
                        var settlements = livingexpenses
                          .Where(x => x.Settlement && !x.Delete)
                          .OrderByDescending(x => x.SettlementNumber)
                          .ToList();
                        // 当前选择年份开账
                        var Checksettlement = livingexpenses
                            .FirstOrDefault(x => x.SettlementNumber == request.SettlementNumber && x.Settlement && !x.Delete);
                        // 当前所选新开账年数据
                        var ChecksettlementById = livingexpenses
                            .FirstOrDefault(x => x.Id == request.OrderId);

                        if (ChecksettlementById == null)
                        {
                            return ApiResult.False("未找到对应的订单");
                        }
                        #region 新版
                        //新年份开账
                        if (Checksettlement == null)
                        {
                            HandleUpdateNewYear<Livingexpenses>(settlements, livingexpenses, ChecksettlementById, request);
                        }
                        else
                        {
                            Checksettlement.Settlement = false;
                            string SettlementNumber = string.Empty;
                            List<Livingexpenses> UpFinanceReimbursementReims = new();
                            var index = settlements.IndexOf(Checksettlement);
                            HandleExistingSettlement(Checksettlement, ChecksettlementById, settlements, index, request, out UpFinanceReimbursementReims, out SettlementNumber);
                            UpdateSettlementRecords(UpFinanceReimbursementReims, SettlementNumber, request);
                        }

                        #endregion
                        // 更新目标记录
                        UpdateTargetRecord(request, ChecksettlementById);

                        // 提交事务
                        _db.SaveChanges();
                        transaction.Commit();
                        return ApiResult.True("修改成功");
                    }
                    catch (Exception ex)
                    {
                        transaction.Rollback();
                        _logger.LogWarning(JsonConvert.SerializeObject(ex));
                        return ApiResult.False($"系统错误: {ex.Message}");
                    }
                }
            }
            catch (Exception e)
            {
                _logger.LogWarning(JsonConvert.SerializeObject(e));
                return ApiResult.False($"系统错误: {e.Message}");
            }
            try
            {

                var Checksettlement = _db.Livingexpenses.FirstOrDefault(x => x.SettlementNumber == request.SettlementNumber   && x.Settlement && !x.Delete  );

                if (Checksettlement != null)
                {
                    Checksettlement.Settlement = false;
                    Checksettlement.SettlementNumber = string.Empty;
                    var livingexpensesInfoList = _db.LivingexpensesInfo.Where(x => x.LivingexpensesId == Checksettlement.Id).ToList();
                    livingexpensesInfoList.ForEach(x =>
                    {
                        x.Settlement = false;
                        x.SettlementNumber = string.Empty;
                    });
                    _db.Livingexpenses.Update(Checksettlement);
                    _db.LivingexpensesInfo.UpdateRange(livingexpensesInfoList);
                }
                 
                var ChecksettlementById = _db.Livingexpenses.FirstOrDefault(x => x.Id == request.OrderId);
                if (ChecksettlementById == null)
                {
                    return ApiResult.True("未找到对应的订单");
                }
                ChecksettlementById.Settlement = true;
                ChecksettlementById.SettlementNumber = request.SettlementNumber;
                var LivingexpensesInfoList = _db.LivingexpensesInfo.Where(x => x.LivingexpensesId == ChecksettlementById.Id).ToList();
                LivingexpensesInfoList.ForEach(x =>
                {
                    x.Settlement = true;
                    x.SettlementNumber = request.SettlementNumber;
                });
                _db.Livingexpenses.Update(ChecksettlementById);
                _db.LivingexpensesInfo.UpdateRange(LivingexpensesInfoList);
                _db.SaveChanges();
                return ApiResult.True();
            }
            catch (Exception e)
            {
                _logger.LogWarning(JsonConvert.SerializeObject(e));
                return ApiResult.True($"系统错误:{e.Message}");
                throw;
            }
        }

        /// <summary>
        /// 添加开账,设置开账数据；
        /// </summary>
        /// <returns></returns>
        [HttpPost("SetSettlement")]
        public ApiResult SetSettlement([FromBody] SetSettlementRequest request)
        {
            try
            {
                using (var transaction = _db.Database.BeginTransaction())
                {
                    try
                    {
                        // 当前所选新开账年数据
                        var ChecksettlementById = _db.Livingexpenses.FirstOrDefault(x => x.Id == request.OrderId && !x.Delete);
                        if (ChecksettlementById == null)
                        {
                            return ApiResult.False("未找到对应的工资单，请检查单据是否已删除");
                        }
                        if (ChecksettlementById.OrderStatus != RealOrderStateEnum.FinanceSuccess)
                        {
                            return ApiResult.False("该单据未进行财务发放操作，请先进行财务发放操作后再进行开账操作");
                        }
                        // 更新目标记录
                        UpdateTargetRecord(request, ChecksettlementById);

                        // 提交事务
                        _db.SaveChanges();
                        transaction.Commit();
                        return ApiResult.True("修改成功");
                    }
                    catch (Exception ex)
                    {
                        transaction.Rollback();
                        _logger.LogWarning(JsonConvert.SerializeObject(ex));
                        return ApiResult.False($"系统错误: {ex.Message}");
                    }
                }
            }
            catch (Exception e)
            {
                _logger.LogWarning(JsonConvert.SerializeObject(e));
                return ApiResult.False($"系统错误: {e.Message}");
            }
        }

        /// <summary>
        /// 修改生活费批号
        /// </summary>
        /// <returns></returns>
        [HttpPost("UpLivingexpenses")]
        public ApiResult UpLivingexpenses([FromBody] UpLivingexpensesRequest request)
        {
            var headRoleId = ConfigurationHelper.GetConfigHeadRoleId("HeadRoleId");
            var financialId = ConfigurationHelper.GetConfigHeadRoleId("FinancialId");
            var author = HttpContext.Request.Headers["Authorization"].ToString().Split(' ')[1];
            var userid = Convert.ToInt32(TokenManage.GetTokenValues(author)[0].Value);
            var role = Convert.ToString((TokenManage.GetTokenValues(author)[2].Value));
            var right = Convert.ToString(TokenManage.GetTokenValues(author)[5].Value);
            var livingexpenses = request.livingexpenses;


            // 数据补录
            //// 获取当前是否是项目负责人 当前时间是否在截止日期前
            //if (right.Contains(headRoleId) && DateTime.Now.Date >= Convert.ToDateTime(request.livingexpenses.LivingeBatch).Date)
            //{
            //    return ApiResult.False("当前批次的提交时间以结束，如需更改请联系管理人员");
            //}


            if (request.UpOrAudit == 1)
            {
                if (DateTime.Now.Date > Convert.ToDateTime(request.livingexpenses.LivingeBatch).Date)
                {
                    //最高权限人员审核
                    if (role.Contains(PublicTool.Admin))
                    {
                        if (livingexpenses.OrderStatus != RealOrderStateEnum.WaitApprove)
                        {
                            return ApiResult.False("当前状态您还不能审批.");
                        }
                        livingexpenses.OrderStatus = RealOrderStateEnum.Success;
                    }//财务审批 
                    else if (right.Contains(financialId))
                    {
                        if (livingexpenses.OrderStatus != RealOrderStateEnum.Success)
                        {
                            return ApiResult.False("当前状态您还不能审批.");
                        }
                        livingexpenses.OrderStatus = RealOrderStateEnum.FinanceSuccess;
                    }
                }
                else {
                    return ApiResult.False("当前时间还未达到审批时间，请在期号日期后进行审批");
                }
              
            }
            else {
                if (livingexpenses.OrderStatus == RealOrderStateEnum.Success && (livingexpenses+""== headRoleId))
                {
                    return ApiResult.False("当前状态您暂无权限修改");
                }
                if (livingexpenses.OrderStatus == RealOrderStateEnum.FinanceSuccess)
                {
                    return ApiResult.False("当前状态您暂无权限修改");
                }
            }
            livingexpenses.OperatDate = DateTime.Now;
            livingexpenses.OperatId = userid;
            _db.Livingexpenses.UpdateRange(livingexpenses);
            List<LivingexpensesInfo> Addinfos = new();
            request.Livingexpensesinfo.ForEach(x => {
                x.Settlement = livingexpenses.Settlement;
                x.SettlementNumber = livingexpenses.SettlementNumber;
                x.OrderStatus = livingexpenses.OrderStatus;
                x.LivingexpensesId = livingexpenses.Id;
                x.OperatId = userid; 
                x.OperatDate = DateTime.Now;
                if (x.Id == 0)
                {
                    Addinfos.Add(x);
                }
            });
            _db.LivingexpensesInfo.UpdateRange(request.Livingexpensesinfo);
            _db.LivingexpensesInfo.AddRange(Addinfos);
            _db.SaveChanges();
            return ApiResult.True();
        }

        /// <summary>
        /// 乐观锁
        /// </summary>
        private static readonly object _locker = new object();
        /// <summary>
        /// 添加生活费数据
        /// </summary>
        /// <returns></returns>
        [HttpPost("AddLivingexpenses")]
        public ApiResult AddLivingexpenses([FromBody] AddLivingexpensesRequest request)
        {
            lock (_locker)
            {

                var headRoleId = ConfigurationHelper.GetConfigHeadRoleId("HeadRoleId");
                var author = HttpContext.Request.Headers["Authorization"].ToString().Split(' ')[1];
                var userid = Convert.ToInt32(TokenManage.GetTokenValues(author)[0].Value);
                var right = Convert.ToString(TokenManage.GetTokenValues(author)[5].Value);
            
                var livingexpensesRequest = request.livingexpenses;
                livingexpensesRequest.OperatDate= DateTime.Now;
                livingexpensesRequest.OperatId= userid;
                _db.Livingexpenses.Add(livingexpensesRequest);
                _db.SaveChanges();

                var maxnumber= _db.Livingexpenses.Max(x => x.SettlementNumber);


                List<LivingexpensesInfo> Upinfos = new();
                request.Livingexpensesinfo.ForEach(x => {
                    x.Settlement = request.livingexpenses.Settlement;
                    //添加对应批次号
                    x.SettlementNumber = maxnumber;
                    x.OrderStatus = livingexpensesRequest.OrderStatus;
                    x.LivingexpensesId = livingexpensesRequest.Id; 
                    x.OperatId = userid;
                    x.OperatDate= DateTime.Now;
                    if (x.Id!=0)
                    {
                        Upinfos.Add(x);
                    }
                });
                _db.LivingexpensesInfo.AddRange(request.Livingexpensesinfo);
                //直接修改  同一个人两个项目
                _db.LivingexpensesInfo.UpdateRange(Upinfos);
                _db.SaveChanges();
            }
            return ApiResult.True();
        }
    }
}
